using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NuGetBatchTool.Services;
using NuGet.Protocol.Core.Types;
using NuGet.Protocol;
using System.Threading;

namespace NuGetBatchTool.Forms
{
    public partial class MainForm : Form
    {
        private readonly NuGetService _nuGetService;
        private string _selectedSource = string.Empty;
        private List<IPackageSearchMetadata> _packages = new();
        private List<IPackageSearchMetadata> _currentVersions = new();

        // 声明控件为字段
        private ComboBox sourceComboBox;
        private ListView packageListView;
        private ListView versionListView;
        private TextBox searchTextBox;
        private Button searchButton;
        private Button backButton;
        private Button hideButton;
        private Button showButton;
        private Label versionTitleLabel;

        public MainForm()
        {
            InitializeComponent();
            _nuGetService = new NuGetService("nuget-sources.ini");
            InitializeControls();
        }

        private void InitializeControls()
        {
            this.Text = "NuGet 包管理工具";
            this.Size = new Size(1000, 600);
            this.StartPosition = FormStartPosition.CenterScreen;

            var toolStrip = new ToolStrip();

            // 搜索框
            searchTextBox = new TextBox();
            searchTextBox.Location = new Point(220, 10);
            searchTextBox.Size = new Size(200, 25);
            searchTextBox.Text = "Jy.Abp";

            // 搜索按钮
            searchButton = new Button();
            searchButton.Text = "搜索";
            searchButton.Location = new Point(430, 10);
            searchButton.Size = new Size(60, 25);
            searchButton.Click += SearchButton_Click;

            // 源选择下拉框
            sourceComboBox = new ComboBox();
            sourceComboBox.DropDownStyle = ComboBoxStyle.DropDownList;
            sourceComboBox.Location = new Point(10, 10);
            sourceComboBox.Size = new Size(200, 25);
            sourceComboBox.SelectedIndexChanged += SourceComboBox_SelectedIndexChanged;

            // 左侧包列表
            packageListView = new ListView();
            packageListView.View = View.Details;
            packageListView.FullRowSelect = true;
            packageListView.GridLines = true;
            packageListView.Location = new Point(10, 50);
            packageListView.Size = new Size(500, 500);
            packageListView.Columns.Add("包名", 220);
            packageListView.Columns.Add("作者", 120);
            packageListView.Columns.Add("描述", 140);
            packageListView.SelectedIndexChanged += PackageListView_SelectedIndexChanged;

            // 右侧包ID标题
            versionTitleLabel = new Label();
            versionTitleLabel.AutoSize = false;
            versionTitleLabel.TextAlign = ContentAlignment.MiddleLeft;
            versionTitleLabel.Font = new Font(Font, FontStyle.Bold);
            versionTitleLabel.Location = new Point(520, 20);
            versionTitleLabel.Size = new Size(400, 25);
            versionTitleLabel.Text = "";
            this.Controls.Add(versionTitleLabel);

            // 右侧版本列表
            versionListView = new ListView();
            versionListView.View = View.Details;
            versionListView.FullRowSelect = true;
            versionListView.GridLines = true;
            versionListView.Location = new Point(520, 50);
            versionListView.Size = new Size(400, 400);
            versionListView.Columns.Add("版本", 120);
            versionListView.Columns.Add("是否显示", 100);
            versionListView.Columns.Add("是否弃用", 100);

            // 操作按钮
            int buttonWidth = 120;
            int buttonHeight = 35;
            int buttonSpacing = 40;
            int versionListViewBottom = versionListView.Location.Y + versionListView.Size.Height;
            int buttonY = versionListViewBottom + 20;
            int buttonStartX = versionListView.Location.X + (versionListView.Width - buttonWidth * 2 - buttonSpacing) / 2;

            hideButton = new Button();
            hideButton.Text = "隐藏版本";
            hideButton.Size = new Size(buttonWidth, buttonHeight);
            hideButton.Location = new Point(buttonStartX, buttonY);
            hideButton.Click += HideButton_Click;
            this.Controls.Add(hideButton);

            showButton = new Button();
            showButton.Text = "显示版本";
            showButton.Size = new Size(buttonWidth, buttonHeight);
            showButton.Location = new Point(buttonStartX + buttonWidth + buttonSpacing, buttonY);
            showButton.Click += ShowButton_Click;
            this.Controls.Add(showButton);

            backButton = new Button();
            backButton.Text = "返回";
            backButton.Location = new Point(340, 470);
            backButton.Size = new Size(80, 30);
            backButton.Visible = false;
            backButton.Click += (s, e) => { ShowMainPackageList(); };

            this.Controls.Add(searchTextBox);
            this.Controls.Add(searchButton);
            this.Controls.Add(sourceComboBox);
            this.Controls.Add(packageListView);
            this.Controls.Add(versionListView);
            this.Controls.Add(backButton);

            LoadSources();
        }

        private void LoadSources()
        {
            sourceComboBox.Items.Clear();
            var sources = _nuGetService.GetSources();
            foreach (var source in sources)
            {
                sourceComboBox.Items.Add(source.Name);
            }
            if (sourceComboBox.Items.Count > 0)
            {
                sourceComboBox.SelectedIndex = 0;
            }
        }

        private async void SearchButton_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_selectedSource))
            {
                MessageBox.Show("请先选择源");
                return;
            }

            var keyword = searchTextBox.Text.Trim();
            if (string.IsNullOrEmpty(keyword))
            {
                MessageBox.Show("请输入搜索关键字");
                return;
            }

            try
            {
                _packages = await _nuGetService.ListPackagesAsync(_selectedSource, keyword);
                RefreshPackageList();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"搜索失败: {ex.Message}");
            }
        }

        private void SourceComboBox_SelectedIndexChanged(object? sender, EventArgs e)
        {
            if (sourceComboBox.SelectedItem != null)
            {
                _selectedSource = sourceComboBox.SelectedItem.ToString() ?? string.Empty;
                LoadAllPackages(searchTextBox.Text.Trim());
            }
        }

        private void RefreshPackageList()
        {
            packageListView.Items.Clear();
            foreach (var package in _packages)
            {
                var item = new ListViewItem(package.Identity.Id);
                item.SubItems.Add(package.Authors);
                item.SubItems.Add(package.Description);
                packageListView.Items.Add(item);
            }
            versionListView.Items.Clear();
        }

        private async void HideButton_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_selectedSource))
            {
                MessageBox.Show("请先选择源");
                return;
            }
            if (packageListView.SelectedItems.Count == 0 || versionListView.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先在左侧选择包，右侧选择要隐藏的包版本");
                return;
            }
            var packageId = packageListView.SelectedItems[0].Text;
            var selectedVersions = versionListView.SelectedItems;
            if (MessageBox.Show($"确定要隐藏选中的 {selectedVersions.Count} 个版本吗？", "确认隐藏", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }
            int successCount = 0;
            int failCount = 0;
            var tasks = new List<Task>();
            foreach (ListViewItem item in selectedVersions)
            {
                var version = item.Text;
                tasks.Add(Task.Run(async () =>
                {
                    try
                    {
                        await _nuGetService.HidePackageAsync(_selectedSource, packageId, version);
                        Interlocked.Increment(ref successCount);
                    }
                    catch (Exception ex)
                    {
                        Interlocked.Increment(ref failCount);
                    }
                }));
            }
            await Task.WhenAll(tasks);
            MessageBox.Show($"隐藏成功 {successCount} 个，失败 {failCount} 个");
            PackageListView_SelectedIndexChanged(null, null); // 刷新版本列表
        }

        private async void ShowButton_Click(object? sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_selectedSource))
            {
                MessageBox.Show("请先选择源");
                return;
            }
            if (packageListView.SelectedItems.Count == 0 || versionListView.SelectedItems.Count == 0)
            {
                MessageBox.Show("请先在左侧选择包，右侧选择要显示的包版本");
                return;
            }
            var packageId = packageListView.SelectedItems[0].Text;
            var selectedVersions = versionListView.SelectedItems;
            if (MessageBox.Show($"确定要显示选中的 {selectedVersions.Count} 个版本吗？", "确认显示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) != DialogResult.Yes)
            {
                return;
            }
            int successCount = 0;
            int failCount = 0;
            var tasks = new List<Task>();
            foreach (ListViewItem item in selectedVersions)
            {
                var version = item.Text;
                tasks.Add(Task.Run(async () =>
                {
                    try
                    {
                        await _nuGetService.UnhidePackageAsync(_selectedSource, packageId, version);
                        Interlocked.Increment(ref successCount);
                    }
                    catch (Exception)
                    {
                        Interlocked.Increment(ref failCount);
                    }
                }));
            }
            await Task.WhenAll(tasks);
            MessageBox.Show($"显示成功 {successCount} 个，失败 {failCount} 个");
            PackageListView_SelectedIndexChanged(null, null); // 刷新版本列表
        }

        private async void LoadAllPackages(string? keyword = null)
        {
            if (string.IsNullOrEmpty(_selectedSource))
                return;

            try
            {
                var allPackages = await _nuGetService.ListPackagesAsync(_selectedSource, keyword ?? "");
                _packages = allPackages
                    .GroupBy(p => p.Identity.Id)
                    .Select(g => g.OrderByDescending(p => p.Identity.Version).First())
                    .ToList();
                ShowMainPackageList();
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载包失败: {ex.Message}");
            }
        }

        private void ShowMainPackageList()
        {
            backButton.Visible = false;
            packageListView.Items.Clear();
            foreach (var package in _packages)
            {
                var item = new ListViewItem(package.Identity.Id);
                item.SubItems.Add(package.Owners);
                item.SubItems.Add(package.Description);
                packageListView.Items.Add(item);
            }
            versionListView.Items.Clear();
        }

        private async void PackageListView_SelectedIndexChanged(object? sender, EventArgs e)
        {
            if (packageListView.SelectedItems.Count == 0) return;
            var packageId = packageListView.SelectedItems[0].Text;
            versionTitleLabel.Text = $"包ID：{packageId}";
            versionListView.Items.Clear();
            try
            {
                _currentVersions = await _nuGetService.ListAllVersionsAsync(_selectedSource, packageId);
                ShowPackageVersions(_currentVersions);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取版本失败: {ex.Message}");
            }
        }

        private void ShowPackageVersions(List<IPackageSearchMetadata> versions)
        {
            versionListView.Items.Clear();
            var items = versions.OrderByDescending(t => t.IsListed)
                //.ThenBy(t => (t as PackageSearchMetadataRegistration)?.DeprecationMetadata)
                .ThenByDescending(x => x.Identity.Version);
            foreach (var v in items)
            {
                var item = new ListViewItem(v.Identity.Version.ToString());
                // 是否显示（已弃用的包一般也会被隐藏，但这里假设有 IsListed 属性，若无则默认"是"）
                string isListed = v.IsListed == false ? "否" : "是";
                string deprecated = "否";
                bool isDeprecated = false;
                if (v is PackageSearchMetadataRegistration reg2 && reg2.DeprecationMetadata != null)
                {
                    deprecated = "是";
                    isDeprecated = true;
                }
                item.SubItems.Add(isListed);
                item.SubItems.Add(deprecated);
                if (isDeprecated)
                {
                    item.ForeColor = Color.Red;
                }
                else if (isListed == "否")
                {
                    item.ForeColor = Color.Goldenrod;
                }
                versionListView.Items.Add(item);
            }
        }
    }
} 